package com.zxy.supplier_system.server.controller

import com.zxy.supplier_system.server.entity.Authority
import com.zxy.supplier_system.server.entity.Goods
import com.zxy.supplier_system.server.service.MarketSaleDocumentService
import com.zxy.supplier_system.server.utils.displayCellString
import org.apache.poi.ss.usermodel.WorkbookFactory
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.http.HttpStatus
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile
import org.springframework.web.server.ResponseStatusException
import java.math.BigDecimal

@RestController
@RequestMapping("markets/accounts/saleDocuments/{documentId}/items")
class MarketSaleDocumentsItemController(
    private val marketSaleDocumentService: MarketSaleDocumentService,
) {

    companion object{
        internal fun importExcelToList(file: MultipartFile): List<SaleDocumentExcelItem> {
            val workbook = WorkbookFactory.create(file.inputStream)
            val sheet = workbook.getSheetAt(0)
            val goodsItems = (1..sheet.lastRowNum).map(sheet::getRow).mapNotNull {
                fun getCellValue(cellIndex: Int): String? {
                    return it.getCell(cellIndex)?.displayCellString?.trim()
                }
                var cellIndex = 0
                val barcode = getCellValue(cellIndex++) ?:throw ResponseStatusException(HttpStatus.BAD_REQUEST,"无效的商品条码，行：${it.rowNum}")
                val amount = getCellValue(cellIndex++)?.toDoubleOrNull()?.toInt() ?: throw ResponseStatusException(HttpStatus.BAD_REQUEST,"无效的商品数量，行：$it")
                val fee = getCellValue(cellIndex)?.toDoubleOrNull()?.toBigDecimal()?: throw ResponseStatusException(HttpStatus.BAD_REQUEST,"无效的金额小计，行：$it")
                SaleDocumentExcelItem(barcode,amount,fee)
            }
            return goodsItems
        }
    }

    data class AddMarketSaleDocumentsItemRequest(
        val goodsId:Int,
        val amount:Int
    )

    @HasAnyAuthority(Authority.卖场_销售单_开单,Authority.卖场_销售单_修改)
    @PostMapping
    fun addItem( @PathVariable documentId: Long,@RequestBody addMarketSaleDocumentsItemRequest: AddMarketSaleDocumentsItemRequest){
        this.marketSaleDocumentService.addItem(documentId,addMarketSaleDocumentsItemRequest)
    }

    @HasAnyAuthority(Authority.卖场_销售单_开单,Authority.卖场_销售单_修改)
    @DeleteMapping("{goodsId}")
    fun deleteItem(@PathVariable goodsId: Int, @PathVariable documentId: Long){
        this.marketSaleDocumentService.deleteItem(documentId,goodsId)
    }

    @Transactional
    class UpdateItemAmountRequest(
        val amount: Int
    )

    @HasAnyAuthority(Authority.卖场_销售单_开单,Authority.卖场_销售单_修改)
    @PatchMapping("{goodsId}/amount")
    fun updateItemAmount(@PathVariable goodsId: Int, @PathVariable documentId: Long,@RequestBody updateItemAmountRequest: UpdateItemAmountRequest){
        return this.marketSaleDocumentService.updateItemAmount(goodsId,documentId,updateItemAmountRequest)
    }

    @HasAuthority(Authority.卖场_销售单_查询)
    @GetMapping
    fun queryOrderItemsInOrder(@PathVariable documentId: Long,pageable: Pageable):Page<OrderItemInOrderSummary>{
        return this.marketSaleDocumentService.queryOrderItemsInOrder(documentId,pageable)
    }

    @HasAnyAuthority(Authority.卖场_销售单_开单,Authority.卖场_销售单_修改,)
    @GetMapping("{goodsId}/exists")
    fun exists(@PathVariable goodsId: Int, @PathVariable documentId: Long): Boolean {
        return this.marketSaleDocumentService.exists(documentId,goodsId)
    }

    @HasAnyAuthority(Authority.卖场_销售单_开单,Authority.卖场_销售单_修改,)
    @GetMapping("barcodes/{barcode}/exists")
    fun exists(@PathVariable barcode: String, @PathVariable documentId: Long): Boolean {
        return this.marketSaleDocumentService.exists(documentId,barcode)
    }

    data class OrderItemInOrderSummary(
        val goodsId:Int,
        val name:String,
        val barcode:String,
        val amountInOrder: Int,
        val inStore:Int,
        val boxSpecification:String?
    ){
        companion object{
            fun fromGoodsAndAmount(goods: Goods,amount:Int): OrderItemInOrderSummary {
                return OrderItemInOrderSummary(
                    goods.id,
                    goods.name,
                    goods.barcode,
                    amount,
                    goods.amount,
                    goods.boxSpecification,
                )
            }
        }
    }

    @HasAnyAuthority(Authority.卖场_销售单_开单,Authority.卖场_销售单_修改)
    @PostMapping("barcodes/{barcode}")
    fun addItem(@PathVariable barcode: String, @PathVariable documentId: Long):OrderItemInOrderSummary{
        return this.marketSaleDocumentService.addItem(documentId,barcode)
    }

    @HasAnyAuthority(Authority.卖场_销售单_开单,Authority.卖场_销售单_修改)
    @PostMapping("goods/{goodsId}")
    fun addItem(@PathVariable goodsId: Int, @PathVariable documentId: Long):OrderItemInOrderSummary{
        return this.marketSaleDocumentService.addItem(documentId,goodsId)
    }

    data class SaleDocumentExcelItem(
        val barcode:String,
        val amount:Int,
        val totalFee:BigDecimal,
    )

    @HasAnyAuthority(Authority.卖场_销售单_修改,Authority.卖场_销售单_开单)
    @PostMapping("excel/import")
    fun importExcel(@RequestParam file: MultipartFile, @PathVariable documentId: Long){
        val goodsItems = importExcelToList(file)

        return this.marketSaleDocumentService.importFromExcel(documentId,goodsItems)
    }




}